<template>
  <div class="o-switch">
    <iSwitch
      :true-value="trueValue"
      :false-value="falseValue"
      v-model="value"
      size="small"
      @on-change="onChange"
      ref="switch"
      :disabled="isDisable"
    ></iSwitch>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { Tsrv, T_srv, ts, ifs, vue } from '@/services';

@T_srv.comp
export default class oSwitch extends vue {
  // modify by wiz
  public compName: string = 'oSwitch';

  /**
   * props
   */
  @T_srv.prop() renderOpts: any;

  @T_srv.prop() params: any;

  private value: any = false;

  private trueValue: any = 1;

  private falseValue: any = 0;

  private isDisable: boolean = true;

  /**
   * data
   */
  @T_srv.watch('params')
  onParamsChange() {
    this.setValue();
    this.setDisable();
  }

  @T_srv.watch('renderOpts', { deep: true })
  onRenderOptsChange() {
    this.setDisable();
  }

  mounted() {
    this.setValue();
    this.setDisable();
  }

  private setDisable() {
    if (!this.params.property) {
      if (this.renderOpts.props.disabled !== true) {
        if (this.params.$table.editConfig) {
          if (
            Tsrv.utils.isFunction(
              this.params.$table.editConfig.beforeEditMethod
            )
          ) {
            const f = this.params.$table.editConfig.beforeEditMethod;
            this.isDisable = !f(this.params);
          }
        }
      }
    } else {
      this.isDisable = !!this.renderOpts.props.disabled;
    }
  }

  public resetValue() {
    this.setValue(this.falseValue);
    this.setTableValue(this.falseValue);
  }

  setValue(val: boolean | string | number | undefined = undefined) {
    if (this.params.property) {
      this.value =
        val !== undefined
          ? val
          : this.params.data[this.params.property] === null
          ? this.falseValue
          : this.params.data[this.params.property] === this.trueValue
          ? 1
          : 0;
    } else {
      this.value =
        val !== undefined
          ? val
          : this.params.row[this.params.column.property] === null
          ? this.falseValue
          : this.params.row[this.params.column.property] === this.trueValue
          ? 1
          : 0;
    }
  }

  setTableValue(val: number | boolean | string) {
    if (this.params.property) {
      this.params.data[this.params.property] = val;
    } else {
      this.params.row[this.params.column.property] = val;
    }
  }

  onChange(e) {
    this.setTableValue(e);
    this.emitEvent('change');
    this.emitEvent('dochange');
  }

  emitEvent(event: string) {
    const ev = this.renderOpts.events;
    const params = Tsrv.utils.cloneNoMatchVue(this.params, true);
    params.from = 'inputtext';
    for (const action in ev) {
      if (ev[action] && action === `on-${event}`) {
        ev[action](params);
      }
    }
  }
}
</script>
